import 'dart:convert';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'network_utils.dart'; // 假设你已经封装了请求工具类
import '../models/user_info_model.dart';
import '../models/home_init_model.dart';
import '../services/home_info_manager.dart';

const String livesTouKey = "livesTouKey";
const String livesTokenKey = "livesTokenKey";
const String livesLocationKey = "livesLocationKey";
const String livesCurrencyKey = "currencyModelKey"; // Currency model key
const String service = "com.94lives.app";

class UserInfos {
  static final UserInfos shared = UserInfos();

  // 用户信息
  MemberInfo? userModel;
  // 用户手机信息
  String userId = "";
  String token = "";
  String productToken = "";
  String location = "";
  String loginPhone = "";
  CurrencyListModel? currencyListModel;

  // 管理器
  final FlutterSecureStorage _secureStorage = FlutterSecureStorage();
  late SharedPreferences _prefs;

  UserInfos() {
    SharedPreferences.getInstance().then((prefs) {
      _prefs = prefs;
      checkAccount();
    });
  }

  // 登录 保存token
  Future<void> saveToken(String stoken) async {
    saveToSecureStorage(livesTokenKey, stoken);
    token = stoken;
    await getUserInfos();
    await refreshToekn();
    // await getMobileInfo();
  }

  // 启动时检查用户信息
  Future<void> checkAccount() async {
    final storageToken = await getFromSecureStorage(livesTokenKey);
    // 检查缓存的 token 和用户信息
    if (storageToken != null && storageToken.isNotEmpty) {
      token = storageToken;
      await getUserInfos();
      await refreshToekn();
    }

    // await getMobileInfo();

  }

  // 获取用户信息
  Function? onRefreshCallback;

  Future<void> getUserInfos() async {
    final response = await NetworkUtils.post(RequestCmd.getUserInfos);
    if (response != null && response['code'] == 200) {
      userModel = MemberInfo.fromJson(response['data']);
      loadInfoAndInit();
      if (userModel?.memberId != 0) {
        userId = userModel?.memberId.toString() ?? '';
        _saveUserInfos(userModel!);
      } else {
        cleanUserInfos();
      }
    } else {
      cleanUserInfos();
    }
  }

  // 获取用户位置
  Future<void> refreshToekn() async {
    await NetworkUtils.post(RequestCmd.refreshs);
  }

  // 更新用户信息
  void _saveUserInfos(MemberInfo model) {
    userId = model.memberId.toString();
    _prefs.setString(livesTokenKey, userId);
    _secureStorage.write(key: userId, value: jsonEncode(model.toJson()));
    
  }

  // 清除用户信息
  Future<void> cleanUserInfos() async {
    await _prefs.remove(livesTokenKey);
    await deleteFromSecureStorage(livesTokenKey);
    await _secureStorage.delete(key: userId);
    userModel = null;
    userId = '';
    token = '';
    loadInfoAndInit();
  }

  Future<void> loadInfoAndInit() async {
    final manager = HomeInfoManager();
      await manager.loadInfoData();
      await manager.loadInitData();

      if(onRefreshCallback != null) {
        onRefreshCallback!();
      }
  }

  // 保存到安全存储
  Future<void> saveToSecureStorage(String key, String value) async {
    await _secureStorage.write(key: key, value: value);
  }

  // 从安全存储获取数据
  Future<String?> getFromSecureStorage(String key) async {
    return await _secureStorage.read(key: key);
  }

  // 删除安全存储数据
  Future<void> deleteFromSecureStorage(String key) async {
    await _secureStorage.delete(key: key);
  }
}

